<?php

/*
 *	Framework namespace
 */
namespace Nano
{
	/*
	 *	Output controll class
	 *
	 *	@extends	\Kernel
	 */
	class Output extends \Kernel
	{
		/*
		 *	$content	string	Buffer
		 */
		public $content;
		
		/*
		 *	$compress	boolean	Enable compress if possible?
		 */
		public $compress = false;
		
		/*
		 *	$compression	boolean	Compression
		 */
		public $compression = false;
		
		/*
		 *	$level	int	Compression level (min. 2, max. 7)
		 */
		public $level = 5;
		
		/*
		 *	$lenght	int	Buffer lenght
		 */
		public $lenght = 0;
		
		/*
		 *	Constructor
		 *
		 *	Start buffering with compression or without
		 */
		public function __construct()
		{
			if(extension_loaded('zlib') && $this->compress &&(getenv('HTTP_ACCEPT_ENCODING') && strpos(getenv('HTTP_ACCEPT_ENCODING'), 'gzip') !== false))
			{
				$this->compression = true;
				
				ob_start('ob_gzhandler', (int)$this->level);
			}
			else
			{
				$this->compression = false;
				
				ob_start();
			}
		}
		
		/*
		 *	Show output and block buffer
		 */
		public function flush()
		{
			$this->lenght = ob_get_length();
			
			$this->content = ob_get_clean();
			
			$this->show();
		}
		
		/*
		 *	Send file
		 *
		 *	@param	string	Path to file
		 */
		public function send($type, $file)
		{
			if(!\Nano\Filesystem::exists($file) || !\Nano\Filesystem::is($type, $file))
			{
				\Nano\Headers::send(404);
			}
			
			Headers::send('Content-type: '.\Nano\Filesystem::mime($file));
			
			$this->content = \Nano\Filesystem::read($file);
		}
		
		/*
		 *	Show content
		 *
		 *	@private
		 */
		private function show()
		{
			if($this->compression)
			{
				Headers::add('Content-Encoding: gzip');
				Headers::add('Content-Length: '.$this->lenght);
				Headers::flush();
			}
			else
			{
				// <bugfix>
				// Headers::add('Content-Encoding: none');
				// So, it's gonna to fail some browsers
				// In this reason it's better fully remove header
				Headers::remove('Content-Encoding');
				// </bugfix>
				Headers::add('Content-Length: '.$this->lenght);
				Headers::flush();
			}
			
			print($this->content);
		}
		
		/*
		 *	Destructor
		 */
		public function __destruct(){}
	}
}